﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.IsolatedStorage;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ForumsBrowser.SiteAccess
{
    static class Persister
    {
        public static void DeleteData(string filename)
        {
            IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForAssembly();
            iso.DeleteFile(filename);
        }

        public static T GetData<T>(string filename) where T : class
        {
            T result = null;

            IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForAssembly();
            if (iso.GetFileNames(filename).Length > 0)
            {
                IsolatedStorageFileStream stream =
                    new IsolatedStorageFileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, iso);
                StreamReader sr = new StreamReader(stream);

                BinaryFormatter bf = new BinaryFormatter();
                try
                {
                    result = (T)bf.Deserialize(stream);
                    
                }
                catch { /* intentionally left blank */ }
                finally
                {
                    stream.Close();
                    stream.Dispose();
                }
            }
            return result;
        }

        public static void SaveData(object data, string filename)
        {

            IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForAssembly();
            IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filename, FileMode.Create, FileAccess.ReadWrite, iso);
            StreamWriter sw = new StreamWriter(stream);
            BinaryFormatter formatter = new BinaryFormatter();

            formatter.Serialize(stream, data);

            sw.Close();
            stream.Close();
            iso.Close();

        }
    }
}
